$(document).ready(function() {

	//document.ready = function() {

	try {

		//GET ALL
		$.ajaxSetup({
			url : "control/masterController.php",
			type : "GET",
			headers : {
				'Accept' : "application/json"
			}
		});

		var myYr;
		var map_canvas;
		var search;

		function updateStatus(message) {
			document.getElementById("status").innerHTML = message;
		}

		function loadDemo() {
			if(navigator.geolocation) {
				updateStatus("");
				//Tom sträng när status är OK
				navigator.geolocation.watchPosition(updateLocation, handleLocationError, {
					maximumAge : 20000

				});
			}
		}


		window.addEventListener("load", loadDemo, true);

		function handleLocationError(error) {
			switch (error.code) {
				case 0:
					updateStatus("Nu blev det ett litet fel när Er lokalalisation skulle hämtas... " + error.message);
					break;

				case 1:
					updateStatus("Användaren förhindrade att sidan hämtade lokalalisation");
					break;

				case 2:
					updateStatus("Webbläsaren kunde inte avgöra Er lokalalisation... " + error.message);
					break;

				case 3:
					updateStatus("Webbläsaren slocknade innan lokalisationen hämtades");
					break;
			}
		}

		function updateLocation(position) {

			var latitude = position.coords.latitude;
			var longitude = position.coords.longitude;
			var accuracy = position.coords.accuracy;
			var timestamp = position.timestamp;

			document.getElementById("latitude").innerHTML = latitude;
			document.getElementById("longitude").innerHTML = longitude;

			try {
				var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
				//Ny google map med idet plus longitude och latitude
				var myOptions = {
					zoom : 10,
					center : latlng,
					mapTypeId : google.maps.MapTypeId.ROADMAP
				};
				var map = new google.maps.Map(document.getElementById("map"), myOptions);
				//myOptions är zoom center osv.
				$('#map').append(map);
				//Hänger på kartan på min DIV med namn map

				var marker = new google.maps.Marker({
					position : latlng,
					map : map,
					title : "Här är Ni!"
				});
				marker.setMap(map);
				// kopplar marker med kartan

			} catch(e) {
				$("#map").append('<p>Unable to retrieve the map</p>');
				$("#map").empty();
				return;
			}
		}

		//navigator.geolocation.getCurrentPosition(updateLocation, handleLocationError);

	} catch (e) {
		$("#list").append('<p>An error occurred!</p>');
		return;
	}

	$('#search').keypress(function(e) {
		if(e.keyCode == 13) {
			$('#cityView').empty();
			$('#message').empty();
			$('#yrWeather').empty();
			$('#mapName').empty();
			$('#mapName').append("<h4>You are still here... You only searched for a different location</h4>");
			e.preventDefault();
			GetGeonamesPosition(this.value);

		}
	});
	function GetGeonamesPosition(data) {
		$.ajaxSetup({
			url : "control/masterController.php?searchcity=" + data,
			type : "GET",
			headers : {
				"Accept" : "application/json"
			}
		});

		$.ajax({
			success : function(data) {
				//console.log("här");
				$('#cityView').empty();
				$('#positionName').empty();
				$('#positionName').append("<h4>Choose desired city</h4>");

				try {
					data = jQuery.parseJSON(data);
					//Parsar datan
					$.each(data, function(key, value) {
						$.each(value, function(i, v) {
							$('#cityView').append("<li><a class='row' href='#city' searchCity='" + v.countryName + "/" + v.adminName1 + "/" + v.toponymName + "'>" + v.countryName + ", " + v.toponymName + ", " + v.adminName1 + "</a></li>");
						});
					});

					$('#cityView').listview('refresh');

					$('.row').live("click", function() {//.row innehåller alla a-taggar i <li> med producerobjektet DEN RÄKNAR ALLT MED KLASSEN ROW
						onClick($(this).attr('searchCity'));

					});
				} catch (e) {
					$("#message").append('<p>the search did not retrieve any data from GeoNames</p>');
					//console.log(e);
					return;
				}
			},
			error : function(object, error) {
				console.log(error);
			}
		});

		function onClick(key) {
			//console.log(key);
			//console.log(data);
			//updateStatus(data);
			$('#cityView').empty();

			document.getElementById("latitude").innerHTML = key;
			document.getElementById("longitude").innerHTML = key;
			GetForecast(key);
			//updateLocation(position);
		}

		function GetForecast(data) {
			$.ajaxSetup({
				url : "control/masterController.php?weather=" + data,
				type : "GET",
				headers : {
					"Accept" : "application/json"
				}
			});

			$.ajax({
				success : function(data) {
					//console.log("här... i GetForecast!");
					//console.log(data);
					$('#cityView').empty();
					$('#yrWeather').empty();
					$('#positionName').empty();
					try {
						//console.log(data);
						data = jQuery.parseJSON(data);

						//simplexml_load_file(data);
						myWeather = data;
						
						$('#yrWeather').append("<h2>" + "Weather for " + data.location.name + " (" + data.location.country + ")" + "</h2>");

						$('#yrWeather').append("<div id='yrWeatherDiv'>");

						$.each(data.forecast.tabular.time, function(key, value) {
	
							if(key < 20) {
							var now = new Date();
							var nowtime = now.toLocaleDateString(now);
							
							var date = new Date(value["@attributes"].from);
							var datetime = date.toLocaleDateString(date);
							
							var time = new Date(value["@attributes"].from);
							var timestamp = time.toLocaleTimeString(time);
							
							var time2 =new Date(value["@attributes"].to);
							var timestamp2 = time2.toLocaleTimeString(time2);
							
							console.log(nowtime);
							
							//console.log(nytt);

								if(value["@attributes"].period == "0") {
									if (datetime == nowtime) {
										$('#yrWeatherDiv').append("<h4 id='tid'>Today</h4>");
									}
									$('#yrWeatherDiv').append("<h4 id='tid'>" + datetime + "</h4>");
									$('#yrWeatherDiv').append("<p>" + timestamp + " - "+ timestamp2+ "</p>");
								}
								else if(value["@attributes"].period == "1") {
									$('#yrWeatherDiv').append("<p>" + timestamp + " - "+ timestamp2+ "</p>");
								}
								else if(value["@attributes"].period == "2") {
									$('#yrWeatherDiv').append("<p>" + timestamp + " - "+ timestamp2+ "</p>");
								}
								else {
									$('#yrWeatherDiv').append("<p>" + timestamp + " - "+ timestamp2+ "</p>");
								}

								if(value.symbol["@attributes"].number == "1") {
									$('#yrWeatherDiv').append("<img src='img/yricons/1.png'/>");

								} else if(value.symbol["@attributes"].number == "2") {
									$('#yrWeatherDiv').append("<img src='img/yricons/2.png'/>");

								} else if(value.symbol["@attributes"].number == "3") {
									$('#yrWeatherDiv').append("<img src='img/yricons/3.png'/>");

								} else if(value.symbol["@attributes"].number == "4") {
									$('#yrWeatherDiv').append("<img src='img/yricons/4.png'/>");

								} else if(value.symbol["@attributes"].number == "5") {
									$('#yrWeatherDiv').append("<img src='img/yricons/5.png'/>");

								} else if(value.symbol["@attributes"].number == "6") {
									$('#yrWeatherDiv').append("<img src='img/yricons/6.png'/>");

								} else if(value.symbol["@attributes"].number == "7") {
									$('#yrWeatherDiv').append("<img src='img/yricons/7.png'/>");

								} else if(value.symbol["@attributes"].number == "8") {
									$('#yrWeatherDiv').append("<img src='img/yricons/8.png'/>");

								} else if(value.symbol["@attributes"].number == "9") {
									$('#yrWeatherDiv').append("<img src='img/yricons/9.png'/>");

								} else if(value.symbol["@attributes"].number == "10") {
									$('#yrWeatherDiv').append("<img src='img/yricons/10.png'/>");

								} else if(value.symbol["@attributes"].number == "11") {
									$('#yrWeatherDiv').append("<img src='img/yricons/11.png'/>");

								} else if(value.symbol["@attributes"].number == "12") {
									$('#yrWeatherDiv').append("<img src='img/yricons/12.png'/>");

								} else if(value.symbol["@attributes"].number == "13") {
									$('#yrWeatherDiv').append("<img src='img/yricons/13.png'/>");

								} else if(value.symbol["@attributes"].number == "14") {
									$('#yrWeatherDiv').append("<img src='img/yricons/14.png'/>");

								} else if(value.symbol["@attributes"].number == "15") {
									$('#yrWeatherDiv').append("<img src='img/yricons/15.png'/>");

								} else {
									$('#yrWeatherDiv').append("<p>" + value.symbol["@attributes"].name + "</p>");
								}

								$('#yrWeatherDiv').append("<p>" + value.temperature["@attributes"].value + "&deg;" + value.temperature["@attributes"].unit + "</p>")
								$('#yrWeatherDiv').append("<hr></hr>");
							}

						});

						$('#yrWeatherDiv').append("</div>");

					} catch (e) {
						$("#message").empty();
						$("#message").append("<p>No weather data was returned from Yr.no</p>");
						console.log(e);
						return;
					}
				},
				error : function(object, error) {
					console.log(error);
				}
			});
		}

	}

});
